package com.haiqiu.security.handle;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.haiqiu.common.result.Constants;
import com.haiqiu.common.utils.web.ResponseUtil;
import com.haiqiu.common.result.ResultCode;
import com.haiqiu.common.result.ResultData;
import com.haiqiu.common.utils.web.JwtTokenUtil;
import com.haiqiu.common.utils.web.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.util.StringUtils;


/**
 * 自定义退出处理类 返回成功
 *
 * @author ruoyi
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String usernameFromToken = jwtTokenUtil.getUsername(request);
        if (!StringUtils.isEmpty(usernameFromToken)) {
            //退出登录，删除缓存token
            redisUtil.del(Constants.REDIS_USER + usernameFromToken);
            //清除缓存的权限数据
            redisUtil.del(Constants.REDIS_USER_AUTH + usernameFromToken);
            //redis缓存用户token
            redisUtil.del(Constants.USER_TOKEN + usernameFromToken);
            //缓存redis用户信息
            redisUtil.del(Constants.REDIS_USER_INFO + usernameFromToken);
            //缓存redis在线用户
            redisUtil.del(Constants.ONLINE_KEY + usernameFromToken);
        }

        ResponseUtil.out(response, ResultData.ok(ResultCode.ACCOUNT_CANCELLED));
    }
}
